package cn.com.hhrcw.enterprise.web;

import cn.com.hhrcw.enterprise.params.OpEntryHistoryParams;
import cn.com.hhrcw.enterprise.vo.OpEntryHistoryVO;
import cn.com.hhrcw.entity.OpEntryHistory;
import cn.com.hhrcw.entity.PiInfo;
import cn.com.hhrcw.mapstruct.EnOpEntryHistoryConvert;
import cn.com.hhrcw.service.IOpEntryHistoryService;
import cn.com.hhrcw.service.IPiInfoService;
import cn.com.hhrcw.sms.service.ISysSmsTemplateService;
import cn.com.hhrcw.utils.EmailSendUtil;
import cn.com.hhrcw.utils.EmailUtil;
import cn.com.hhrcw.utils.NewsUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.File;
import java.util.Map;

/**
 * 职位-入职邀请
 *
 * @author jiangdong
 * @since 2020-10-29
 */
@RestController
@Slf4j
@RequestMapping("/en/opEntryHistory")
@Api(tags = "职位-入职邀请")
@Validated
public class EnOpEntryHistoryController extends JeecgController<OpEntryHistory, IOpEntryHistoryService> {

    @Autowired
    private IOpEntryHistoryService opEntryHistoryService;

    @Autowired
    private EnOpEntryHistoryConvert opEntryHistoryConvert;

    @Autowired
    NewsUtil newsUtil;
    @Autowired
    private EmailUtil emailUtil;

    @Autowired
    private ISysSmsTemplateService templateService;

    @Autowired
    private IPiInfoService piInfoService;
    @Autowired
    private EmailSendUtil emailSendUtil;

    /**
     * 添加入职邀请
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/add")
    @AutoLog(logType = 2, ty = "insert", value = "发送入职邀请")
    @ApiOperation(value = "添加", notes = "添加")
    public Result<?> add(@RequestBody @Valid OpEntryHistoryParams params) {
        int count = service.lambdaQuery().eq(OpEntryHistory::getJobId, params.getJobId()).eq(OpEntryHistory::getUserId, params.getUserId()).eq(OpEntryHistory::getDelFlag, false).count();
        if (count > 0) {
            return Result.error("已经发过入职邀请，请不要重复发送");
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        OpEntryHistory opEntryHistory = opEntryHistoryConvert.toEntity(params);
        opEntryHistory.setCreateBy(sysUser.getId());
        opEntryHistory.setCreateTime(DateUtil.date());
        opEntryHistory.setDelFlag(false);

        boolean saved = opEntryHistoryService.save(opEntryHistory);
        Map<String, String> map = emailUtil.creatEmail(opEntryHistory.getUserId(), sysUser.getId(), null, null, opEntryHistory.getId(), "2");
        String title = map.get("tittle");
        String content = map.get("content");
        PiInfo piInfo = piInfoService.lambdaQuery().eq(PiInfo::getUserId, opEntryHistory.getUserId()).one();
        //短信
        templateService.sendSms(new String[]{piInfo.getPhone()}, "【" + title + "】" + content);

        if (params.getEmailFlag() != null && params.getEmailFlag()) {
            //邮件
            Map<String, String> map1 = emailSendUtil.creatEmail(opEntryHistory.getUserId(), sysUser.getId(), null, null, opEntryHistory.getId(), "2");
            String title1 = map1.get("tittle");
            String content1 = map1.get("content");
            templateService.sendEmail(content1, title1, (File) null, piInfo.getEmail());
        }
        //生成系统消息
        newsUtil.creatNews(params.getUserId(), sysUser.getId(), 0, 1, opEntryHistory.getId(), "2");
        return saved ? Result.ok() : Result.error("添加失败");
    }

    /**
     * 根据id查询录用信息
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    @AutoLog(logType = 2, ty = "visit", value = "入职邀请查询")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    @PermissionData
    public Result<OpEntryHistoryVO> queryById(String id) {
        OpEntryHistory opEntryHistory = opEntryHistoryService.lambdaQuery().eq(OpEntryHistory::getId, id).eq(OpEntryHistory::getDelFlag, false).one();
        if (opEntryHistory == null) {
            throw new JeecgBootException("数据不存在");
        }
        return Result.ok(opEntryHistoryConvert.toVO(opEntryHistory));
    }

    /**
     * 编辑录用信息
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/edit")
    @AutoLog(logType = 2, ty = "update", value = "入职邀请编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    @RequiresPermissions("opEntryHistory:edit")
    public Result<?> edit(@RequestBody @Valid OpEntryHistoryParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        OpEntryHistory opEntryHistory = opEntryHistoryConvert.toEntity(params);
        opEntryHistory.setUpdateBy(sysUser.getId());
        opEntryHistory.setUpdateTime(DateUtil.date());

        boolean updated = opEntryHistoryService.updateById(opEntryHistory);
        return updated ? Result.ok() : Result.error("编辑失败");
    }

    /**
     * 批量删除
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/delete")
    @AutoLog(logType = 2, ty = "delete", value = "入职邀请删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @RequiresPermissions("opEntryHistory:delete")
    public Result delete(String[] id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaUpdateWrapper<OpEntryHistory> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(OpEntryHistory::getId, id).set(OpEntryHistory::getDelFlag, true).set(OpEntryHistory::getUpdateBy, sysUser.getUsername()).set(OpEntryHistory::getUpdateTime, DateUtil.date());

        boolean deleted = opEntryHistoryService.update(updateWrapper);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

}
